package com.example.test.db;



import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.test.bean.GW;

import java.util.ArrayList;
import java.util.List;

public class DBOpenHelper extends SQLiteOpenHelper {
    /**
     * 声明一个AndroidSDK自带的数据库变量db
     */
    private SQLiteDatabase db;
    private static final String DB_NAME= "db_test.db";
    private static final String TABLE_NAME_GW = "user";
    private static final String CREATE_TABLE_SQL = "create table " +TABLE_NAME_GW + "(id integer primary key autoincrement, name text,password text,email text,phone text)";

    public DBOpenHelper(Context context){
        super(context, DB_NAME, null,1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


    public long insert(User user){
        db=getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name",user.getName());
        values.put("password",user.getPassword());
        values.put("email",user.getEmail());
        values.put("phone",user.getPhone());
        return db.insert(TABLE_NAME_GW,null,values);
    }


    public List<User> query(String name){
        db=getWritableDatabase();
        List<User> list = new ArrayList<>();
        Cursor cursor=db.query(TABLE_NAME_GW,null,"phone like?",new String[]{name+""},null,null,null);
        if (cursor!=null){
            while (cursor.moveToNext()){
                @SuppressLint("Range") String phone=cursor.getString(cursor.getColumnIndex("phone"));
                @SuppressLint("Range") String name1=cursor.getString(cursor.getColumnIndex("name"));
                @SuppressLint("Range") String password=cursor.getString(cursor.getColumnIndex("password"));
                @SuppressLint("Range") String email=cursor.getString(cursor.getColumnIndex("email"));
                User user=new User();
                user.setPhone(phone);
                user.setPassword(password);
                user.setName(name1);
                user.setEmail(email);
                list.add(user);
            }
            cursor.close();
        }
        return list;
    }

    public int update(User user){
        SQLiteDatabase db = getWritableDatabase();
        ContentValues values = new ContentValues();//数据分装，用来存数据
        values.put("phone",user.getPhone());
        values.put("name",user.getName());
        values.put("email", user.getEmail());
        return db.update(TABLE_NAME_GW,values,"phone like ?",new String[]{user.getPhone()});
    }
}

